// timetable.js
import Toast from '@vant/weapp/toast/toast';
import { getTimetable } from '../../utils/api-v2';

Page({
  data: {
    currentWeek: 1,
    weekDays: ['一', '二', '三', '四', '五', '六', '日'],
    timeSlots: [
      { label: '1', time: '08:00' },
      { label: '2', time: '08:50' },
      { label: '3', time: '10:00' },
      { label: '4', time: '10:50' },
      { label: '5', time: '14:00' },
      { label: '6', time: '14:50' },
      { label: '7', time: '16:00' },
      { label: '8', time: '16:50' },
      { label: '9', time: '19:00' },
      { label: '10', time: '19:50' }
    ],
    timetableData: {},
    showDetail: false,
    selectedCourse: null
  },

  onLoad() {
    console.log('========== 课表页面加载 ==========');
    console.log('weekDays:', this.data.weekDays);
    console.log('weekDays 长度:', this.data.weekDays.length);
    console.log('timeSlots:', this.data.timeSlots);
    console.log('timeSlots 长度:', this.data.timeSlots.length);
    console.log('====================================');
    this.loadTimetable();
  },

  onShow() {
    // 每次显示页面时刷新课表（可能有新选的课）
    this.loadTimetable();
  },

  // 加载课表
  loadTimetable() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });

    // 调用接口 GET /student/timetable
    getTimetable()
      .then((res) => {
        Toast.clear();
        
        console.log('========== 课表 完整 API 返回 ==========');
        console.log('完整响应:', JSON.stringify(res, null, 2));
        
        // 处理后端返回的课表数据
        const courses = res.data || [];
        console.log('========== 第一个课程的所有字段 ==========');
        if (courses[0]) {
          Object.keys(courses[0]).forEach(key => {
            console.log(`${key}: ${courses[0][key]}`);
          });
        }
        console.log('==========================================');
        
        // 如果 API 返回空，尝试从我的课程生成
        if (courses.length === 0) {
          console.log('课表API返回空，尝试从本地课程生成');
          this.loadFromMyCourses();
          return;
        }
        
        const timetableData = {};
        
        // 将课程转换为课表格式（按单节填充）
        courses.forEach(course => {
          console.log('解析课程:', course.courseName, course.time);
          const timeInfo = this.parseTime(course.time);
          console.log('解析结果:', timeInfo);
          
          if (timeInfo && timeInfo.sections) {
            // 为每一节课都添加课程
            timeInfo.sections.forEach(section => {
              const key = `${section}-${timeInfo.dayIndex}`;
              timetableData[key] = {
                name: course.courseName,
                teacher: course.teacherName,
                location: course.location,
                time: course.time,
                credit: course.credit
              };
              console.log(`添加课程到位置 第${section}节-周${timeInfo.dayIndex + 1}`);
            });
          }
        });

        console.log('========== 最终课表数据 ==========');
        console.log('timetableData:', timetableData);
        console.log('数据键列表:', Object.keys(timetableData));
        console.log('键值对详情:');
        Object.keys(timetableData).forEach(key => {
          console.log(`  ${key}:`, timetableData[key].name);
        });
        console.log('====================================');
        
        if (Object.keys(timetableData).length === 0) {
          console.log('解析后课表为空，尝试从本地课程生成');
          this.loadFromMyCourses();
        } else {
          console.log('设置课表数据到页面...');
          this.setData({ timetableData }, () => {
            console.log('setData 完成');
            // 测试访问
            console.log('测试访问 1-0:', this.data.timetableData['1-0']);
            console.log('测试访问 2-1:', this.data.timetableData['2-1']);
          });
        }
      })
      .catch((err) => {
        Toast.clear();
        console.error('加载课表失败:', err);
        this.loadFromMyCourses();
      });
  },

  // 从我的课程加载课表
  loadFromMyCourses() {
    const myCourses = wx.getStorageSync('myCourses') || [];
    console.log('从本地课程生成课表，课程数:', myCourses.length);
    
    if (myCourses.length === 0) {
      Toast('暂无课程');
      return;
    }
    
    const timetableData = {};
    
    myCourses.forEach(course => {
      console.log('本地课程:', course.courseName, course.time);
      const timeInfo = this.parseTime(course.time);
      console.log('解析结果:', timeInfo);
      
      if (timeInfo && timeInfo.sections) {
        // 为每一节课都添加课程
        timeInfo.sections.forEach(section => {
          const key = `${section}-${timeInfo.dayIndex}`;
          timetableData[key] = {
            name: course.courseName,
            teacher: course.teacherName,
            location: course.location || '待定',
            time: course.time,
            credit: course.credit
          };
        });
      }
    });

    console.log('本地生成的课表数据:', timetableData);
    
    if (Object.keys(timetableData).length === 0) {
      Toast('课程时间信息不完整');
    } else {
      this.setData({ timetableData });
      Toast('使用本地数据');
    }
  },

  // 解析时间字符串
  parseTime(timeStr) {
    if (!timeStr) return null;

    console.log('parseTime 输入:', timeStr);

    // 格式: "4-5-4" => 周4，第5节开始，持续4节课（即5,6,7,8节）
    const numMatch = timeStr.match(/^(\d+)-(\d+)-(\d+)$/);
    if (numMatch) {
      const day = parseInt(numMatch[1]);        // 周几 (1-7)
      const startSlot = parseInt(numMatch[2]);  // 开始节次 (1-10)
      const duration = parseInt(numMatch[3]);   // 持续节数
      
      console.log('数字格式匹配:', { day, startSlot, duration });
      console.log(`含义: 周${day}，第${startSlot}节开始，上${duration}节课（${startSlot}-${startSlot + duration - 1}节）`);
      
      // 周几转换: 1=周一, 2=周二, ..., 7=周日
      const dayIndex = day - 1;  // 转换为数组索引 (0-6)
      
      // 计算课程占用的所有节次
      const sections = [];
      for (let i = 0; i < duration; i++) {
        const currentSection = startSlot + i;
        if (currentSection >= 1 && currentSection <= 10) {
          sections.push(currentSection);
        }
      }
      
      console.log('占用的节次:', sections);
      
      // 验证范围
      if (dayIndex >= 0 && dayIndex < 7 && sections.length > 0) {
        return { dayIndex, sections };  // 返回具体节次数组
      }
      
      console.log('超出范围!');
      return null;
    }

    // 格式2: "周一 1-2节" (旧格式，保持兼容)
    const weekDayMap = {
      '周一': 0, '周二': 1, '周三': 2, '周四': 3, '周五': 4,
      '周六': 5, '周日': 6
    };

    // 匹配格式: "周X X-X节"
    const match = timeStr.match(/(周[一二三四五六日])\s*(\d+)-(\d+)节/);
    if (match) {
      const weekDay = match[1];
      const startSection = parseInt(match[2]);
      const endSection = parseInt(match[3]);
      
      const dayIndex = weekDayMap[weekDay];

      if (dayIndex !== undefined) {
        const sections = [];
        for (let i = startSection; i <= endSection; i++) {
          sections.push(i);
        }
        return { dayIndex, sections };
      }
    }

    console.log('无法解析时间格式:', timeStr);
    return null;
  },

  // 获取课程
  getCourse(section, dayIndex) {
    const key = `${section}-${dayIndex}`;
    return this.data.timetableData[key] || null;
  },

  // 获取课程样式类
  getCourseClass(section, dayIndex) {
    return this.getCourse(section, dayIndex) ? 'has-course' : '';
  },

  // 显示课程详情
  showCourseDetail(e) {
    const { slot, day } = e.currentTarget.dataset;
    const course = this.getCourse(slot, day);
    
    if (course) {
      this.setData({
        selectedCourse: course,
        showDetail: true
      });
    }
  },

  // 关闭详情
  closeDetail() {
    this.setData({
      showDetail: false
    });
  },

  // 上一周
  prevWeek() {
    if (this.data.currentWeek > 1) {
      this.setData({
        currentWeek: this.data.currentWeek - 1
      });
      this.loadTimetable();
    } else {
      Toast('已经是第一周了');
    }
  },

  // 下一周
  nextWeek() {
    if (this.data.currentWeek < 20) {
      this.setData({
        currentWeek: this.data.currentWeek + 1
      });
      this.loadTimetable();
    } else {
      Toast('已经是最后一周了');
    }
  }
});
